package com.house.service.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.house.common.context.BaseContext;
import com.house.common.exception.HouseException;
import com.house.common.result.HttpCodeEnum;
import com.house.model.dto.HouseImageDto;
import com.house.model.entity.HouseImage;
import com.house.model.vo.HouseImageVo;
import com.house.service.mapper.HouseImageMapper;
import com.house.service.service.IHouseImageService;
import com.house.util.COSUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class HouseImageServiceImpl extends ServiceImpl<HouseImageMapper, HouseImage> implements IHouseImageService {

    @Autowired
    private HouseImageMapper houseImageMapper;

    @Autowired
    private COSUtil cosUtil;

    @Override
    public String uploadHeadImage(MultipartFile file, String houseId) {
        String url = cosUtil.upload(file);
        return url;
    }

    @Override
    public HouseImageVo saveHouseImages(MultipartFile file, String houseId) {
        String url = cosUtil.upload(file);
        HouseImage houseImage = new HouseImage();
        houseImage.setHouseId(houseId);
        houseImage.setUrl(url);
        houseImage.setCreateDate(new Date(System.currentTimeMillis()));
        String currentId = BaseContext.getCurrentId();
        houseImage.setCreatePerson(currentId);
        houseImage.setSort(1);
        int insert = houseImageMapper.insert(houseImage);
        if (insert < 1) {
            throw new HouseException(HttpCodeEnum.ERROR);
        }
        HouseImageVo houseImageVo = new HouseImageVo();
        houseImageVo.setId(houseImage.getId());
        houseImageVo.setUrl(url);
        houseImageVo.setHouseId(houseId);
        return houseImageVo;
    }

    @Override
    public void removeHouseImage(HouseImageDto dto) {
        houseImageMapper.deleteHouseImage(dto);
    }

    @Override
    public List<HouseImageVo> getHouseImageByHouseId(String houseId) {
        List<HouseImageVo> houseImageVos = houseImageMapper.selectHouseImageVoByHouseId(houseId);
        return houseImageVos;
    }
}
